<?php

namespace App\Criteria;

use Prettus\Repository\Contracts\CriteriaInterface;
use Prettus\Repository\Contracts\RepositoryInterface;

/**
 * Class JoinableCriteria.
 *
 * @package namespace App\Criteria;
 */
class JoinableCriteria implements CriteriaInterface
{

    protected $joinInfo;

    public function __construct(array $joinInfo = [])
    {
        $this->joinInfo = $joinInfo;
    }

    /**
     * Apply criteria in query repository
     *
     * @param string              $model
     * @param RepositoryInterface $repository
     *
     * @return mixed
     */
    public function apply($model, RepositoryInterface $repository)
    {
        if (method_exists($model->getModel(), 'wantsJoin')) {
            $info = $model->getModel()->wantsJoin();
        } else {
            $info = $this->joinInfo;
        }
        foreach ($info as $join) {
            switch ($join['type']) {
                case 'inner':
                    $method = 'join';
                    break;
                case 'left':
                    $method = 'leftJoin';
                    break;
                case 'right':
                    $method = 'rightJoin';
                    break;
                default:
                    $method = 'join';
                    break;
            }
            $model->$method(
                $join['table'],
                $model->getModel()->getTable().'.'.$model->getModel()->getKeyName(),
                '=',
                "{$join['table']}.{$join['field']}"
            );
        }
        return $model;
    }
}
